#include <iostream>
#include <thread>
#include <memory>
#include <functional>
#include <mutex>
#include <vector>
#include <condition_variable>
#include <atomic>
#include <future>

class ThreadPool
{
    using func_t = std::function<void()>;
public:
    ThreadPool(int num = 5)
        :_stop(false)
    {
        for(int i = 0; i < num; i++)
            _threads.emplace_back(&ThreadPool::Entry, this);    //push_back要怎么写
            // _threads.push_back(std::thread(Entry, this));    //push_back ,右值传参，默认移动构造(T&&)
    }
    ~ThreadPool()
    {
        Stop(); 
    }
    void Stop() 
    {
        if(_stop == true) return; //防止手动 stop 和 析构 重复jion
        _stop = true;
        _cv.notify_all();
        for(auto &thread : _threads) //线程没有拷贝构造
            thread.join();
    }
    template<typename F, typename ...Args>
    auto Push(F &&func, Args&& ...args) -> std::future<decltype(func(args...))>
    {
        //用智能指针管理 func
        using return_type = decltype(func(args...));  //func的类型
        auto newfunc = std::bind(std::forward<F>(func), std::forward<Args>(args)...); //func的无参对象
        auto ptask = std::make_shared<std::packaged_task<return_type()>>(newfunc);  //管理完毕
        std::future<return_type> fu = ptask->get_future();         //关连
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _tasks.push_back([ptask](){ (*ptask)();});
            _cv.notify_one();
        }
        return fu;
    }
private:
    void Entry()
    {
        while(!_stop)
        {
            std::vector<func_t> tasks;
            {
                std::unique_lock<std::mutex> lock(_mutex);
                _cv.wait(lock, [this](){ return _stop || !_tasks.empty();});
                tasks.swap(_tasks);
            }
            for(auto & task : tasks)
                task();
        }
    }
private:
    std::atomic<bool> _stop;
    std::vector<func_t> _tasks; //存func_t这样类型的函数
    std::mutex _mutex;
    std::condition_variable _cv;
    std::vector<std::thread> _threads;
};
int Add(int num1, int num2)
{
    return num1 + num2;
}
int main()
{
    ThreadPool tp;
    for(int i = 0; i < 10; i++)
    {
        std::future<int> fu = tp.Push(Add, i, i);
        std::cout << fu.get() << std::endl;
    }
    tp.Stop();
    return 0;
}